package com.lzy.sso.cas.principle;

import lombok.ToString;

import java.util.*;

/**
 * @Author: lzy
 * @Date: 2022/4/30 22:47
 * @Description:
 */

@ToString
public class Principle {
    // 基本信息
    private BasePrinciple basePrinciple;
    // 角色信息
    private RolePrinciple rolePrinciple;

    protected Principle(){}

    protected Principle(Map<String,Object> map,Set<String> set){
        if(map!=null) {
            this.basePrinciple = new BasePrinciple(map);
        }
        if(set!=null) {
            this.rolePrinciple = new RolePrinciple(set);
        }
    }

    /**
     * 个人信息获取
     * @param name
     * @return
     */
    public Object getBaseInfo(String name){
        if(basePrinciple==null){
            return null;
        }

        return basePrinciple.getAttribute(name);
    }

    public Map<String,Object> getAllBaseInfo(){
        if(basePrinciple==null)
            return null;
        return basePrinciple.getPrototype();
    }

    /**
     * 角色相关信息
     * @param role
     * @return
     */
    public boolean hasRole(String role){
        return rolePrinciple==null?false:rolePrinciple.hasRole(role);
    }

    public Set<String> getRoles(){
        return rolePrinciple==null?null:rolePrinciple.getRoles();
    }

    /**
     * 个人信息保存实体
     */
    @ToString
    private static class BasePrinciple {
        private Map<String,Object> info;

        public BasePrinciple(Map<String,Object> map){
            info=new HashMap<>(map);
        }

        public Object getAttribute(String name){
            return info.get(name);
        }

        public Map<String,Object> getPrototype(){
            return new HashMap<>(info);
        }
    }

    /**
     * 角色信息保存实体
     */
    @ToString
    private static class RolePrinciple {
        private Set<String> roles;

        public RolePrinciple(Set<String> set){
            roles=new HashSet<>(set);
        }

        public boolean hasRole(String role){
            return roles.contains(role);
        }

        public Set<String> getRoles(){
            return new HashSet<>(roles);
        }
    }
}
